var db = require('../tools/db');
var author = require('../models/author');
var admin = require('./admin');


module.exports = function(app) {

	app.get('/', function(req, res) {

		res.render('index', {
			title: 'Express'
		});
	});

	app.get('/author/:id', function(req, res) {
		author.findById(req.params.id, function(err, r) {
			res.json(r);
		});
	});

	app.get('/login', function(req, res) {
		res.render('login');
	});

	app.post('/login', function(req, res) {
		//判断用户名密码
		author.checkAuth(req.body.username, req.body.password, function(err, r) {
			if (err) {
				req.flash('_message', err);
				res.locals.message = req.flash('_message');
				return res.render('login');
			}
			console.log(r[0]);
			// 将用户信息写入 session
			req.session.auth = r[0];
			// 如果存在原始请求路径，将用户重定向到原始请求路径
			var redirectUrl = '/';
			if (req.session.originalUrl) {
				redirectUrl = req.session.originalUrl;
				// 清空 session 中存储的原始请求路径
				req.session.originalUrl = null;
			}
			res.redirect(redirectUrl);
		});
	});

	app.get('/logout', function(req, res) {
		req.session.auth = null;
		res.redirect('/');
	});

	app.use('/admin', admin);

	//404处理
	app.use(function(req, res) {
		res.status(400);
		res.render('404');
	});
	//500处理
	app.use(function(error, req, res, next) {
		res.status(500);
		res.render('500', {
			error: error
		});
	});

};